package encrypt.demo;

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;
import java.util.Date;

public class RSADemo {

    public static void main(String[] args) throws Exception {
        long init_start = new Date().getTime();
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // 设置密钥长度为2048位
        KeyPair keyPair = keyGen.generateKeyPair();
        Cipher cipher = Cipher.getInstance("RSA");
        long init_end = new Date().getTime();
        System.out.println("init_cost_time:"+(init_end-init_start));

        //测试加密
        long en_begin = new Date().getTime();
        cipher.init(Cipher.ENCRYPT_MODE,keyPair.getPublic());
        byte[] encrypted_bytes = cipher.doFinal("this is test msg.".getBytes());
//        for (int i = 0; i < 100; i++) {
//            cipher.doFinal(("this is a test msg"+i).getBytes());
//        }
        String encoded_string = Base64.getEncoder().encodeToString(encrypted_bytes);
        long en_end  = new Date().getTime();
        System.out.println(en_end-en_begin);
        System.out.println(encoded_string);


        //测试解密
        long de_start = new Date().getTime();
        cipher.init(Cipher.DECRYPT_MODE,keyPair.getPrivate());
        byte[] decrypted_bytes = cipher.doFinal(Base64.getDecoder().decode(encoded_string));
        long de_end = new Date().getTime();
        System.out.println(de_end-de_start);
        System.out.println(new String(decrypted_bytes));

    }
}
